package guzb.cnblogs.security.industrydemo.auth.restful;

import com.fasterxml.jackson.annotation.JsonIgnore;
import guzb.cnblogs.security.industrydemo.auth.MyUserDetails;
import guzb.cnblogs.security.industrydemo.auth.UserEntity;
import org.springframework.security.authentication.AbstractAuthenticationToken;

/**
 * 自定义的认证对象
 */
public class MyUsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {

    @JsonIgnore
    private String username;

    @JsonIgnore
    private String password;

    private String token;

    private UserEntity user;

    /**
     * 基于用户名密码的构造函数，用于在认证前创建认证对象，将其传递给AuthenticationManager进行认证
     * @param username 用户名
     * @param password 密码
     */
    public MyUsernamePasswordAuthenticationToken(String username, String password) {
        super(null);
        this.username = username;
        this.password = password;
    }

    /**
     * 基于token和用户信息的构造器，这主要用在认证通过以后生成新的认证对象
     * @param token 认证成功后，获得的标识串
     * @param userDetails 用户详细信息
     */
    public MyUsernamePasswordAuthenticationToken(String token, MyUserDetails userDetails) {
        super(userDetails.getAuthorities());
        this.token = token;
        this.user = userDetails.getUserEntity();
        this.username = this.user.getUsername();
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return this.password;
    }

    @Override
    public Object getPrincipal() {
        return this.username;
    }

    @Override
    public String getName() {
        return this.user == null ? null : this.user.getName();
    }

    public String getToken() {
        return token;
    }

    public String getUsername() {
        return username;
    }

    public UserEntity getUser() {
        return user;
    }
}
